import JSZip from "jszip";
import { saveAs } from 'file-saver';
import docxtemplater from 'docxtemplater'
import html2pdf from 'html2pdf.js'
import ImageModule from 'docxtemplater-image-module-free'
import jsbarcode from 'jsbarcode'
import Pizzip from 'pizzip'
import column_inspection_plan from "./column_inspection_plan";
import {
    binaryToBlob,
    base64Parser,
    blobToArrayBuffer,
    dataToXlsxBlob
} from './utils'
import {generateHtmlStr} from './utils'
import {ElMessage} from "element-plus";

const DOC_TEMPLATE_URL = {
    // 产品条码
    productBarCode: 'https://xc-goods.oss-cn-shenzhen.aliyuncs.com/20231031/data/Company/20231031201527524a92cd09b68108d873348666a854b92ad.docx',
    // 备库单号
    orderNo: 'https://xc-goods.oss-cn-shenzhen.aliyuncs.com/20231102/data/Company/2023110214010794000d429aae19e3617b77a75689469f69c.docx'
}

const CANVAS_ID = 'labelInfoDownloadBarCode'

const generateBarCode = txt => {
    const canvas = document.createElement('canvas')
    canvas.setAttribute('id', CANVAS_ID)
    jsbarcode(canvas, txt, {
        width: 2,
        height: 60,
        fontSize: 23,
        format: 'CODE128',
        fontOptions: "bold",
        textMargin: 0
        // displayValue: false
    })
    return canvas.toDataURL()
}

/**
 * 创建html元素 并生成pdf 返回blob类型
 * @param innerHTML
 */
const generatePdfToBlob = async (innerHTML, optionsData = {}) => {
    const content = document.createElement('div')
    content.innerHTML = innerHTML
    const options = {
        // margin: 0.15,
        // pagebreak: { mode: ['avoid-all', 'css', 'legacy'] },
        image: { type: 'jpeg', quality: 1 },
        html2canvas: { scale: 20 },
        jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' },
        ...optionsData
    }
    return await html2pdf().from(content).set(options).output('blob')
}

const clearCanvasDom = (id = CANVAS_ID) => {
    const element = document.getElementById(CANVAS_ID)
    if (element) element.parentNode.removeChild(element)
}


const imageOptions = {
    getImage(tag) {
        return base64Parser(tag);
    },
    getSize() {
        return [170, 75];
    },
}

const folderConfig = [
    {
        folderName: '产品条码',
        generateFile: async (zip, data) => {
            const { details, order_type } = data;
            await Promise.all(details.map(async item => {
                const { fn_sku, sku_en_title, sku, quantity, link, custom_sku } = item
                try {
                    let pdf
                    // if (order_type === 0) { // fba单据
                    //     const barCode = generateBarCode(fn_sku)
                    //     pdf = await generatePdfToBlob(generateHtmlStr.productCode(
                    //         {barCode, fn_sku, sku_en_title, quantity, custom_sku, sku}
                    //     ), {
                    //             jsPDF: { unit: 'mm', format: [50, 70], orientation: 'landscape' }
                    //         })
                    // } else {
                    //     if (link) {
                    //
                    //     }
                    // }
                    const res = await fetch(link)
                    pdf = await res.blob()
                    if (pdf) zip.file(`${fn_sku}.pdf`, pdf)
                } catch (error) {
                    console.error('Error generating file:', error)
                    console.error(error.stack)
                }
            }));
        },
    },
    {
        folderName: '透明标签',
        generateFile: async (zip, data, order_type) => {
            const { details } = data;
            await Promise.all(details.map(async (item) => {
                const { transparent_label_link, sku, quantity } = item
                if (transparent_label_link) {
                    const res = await fetch(transparent_label_link)
                    const blob = await res.blob()
                    const fileExtension = transparent_label_link.split('.').pop()
                    await zip.file(`${sku}_${quantity}PCS${fileExtension ? `.${fileExtension}` : ''}`, blob)
                }
            }));
        },
    },
    {
        folderName: '外箱标（欧代-英代）',
        generateFile: async (zip, data) => {
            const { details } = data
            await Promise.all(details.map(async item => {
                const { sku, quantity } = item;
                try {
                    const pdf = await generatePdfToBlob(generateHtmlStr.ukProxy({
                        data: item.data, country: data.country
                    }))
                    zip.file(`${sku} ${quantity}.pdf`, pdf)
                } catch (error) {
                    console.error('Error generating file:', error)
                    console.error(error.stack) // Log the stack trace
                }
            }))
        }
    },
    {
        folderName: '物流箱唛（日本）',
    },
    {
        folderName: '外箱唛',
        generateFile: async (zip, data) => {
            const { out_carton_label } = data
            await Promise.all(out_carton_label.map(async (item, index) => {
                const { fn_sku, sku_en_title, sku, total_box_count, to_order_no } = item;
                const res = await fetch(DOC_TEMPLATE_URL.orderNo);
                const b = await res.blob();
                const buf = await blobToArrayBuffer(b)
                const pzip = new Pizzip(buf);
                const doc = new docxtemplater(pzip, {
                    paragraphLoop: true,
                    linebreaks: true,
                });
                doc.render({
                    fn_sku,
                    sku,
                    shipment_id: to_order_no,
                    quantity: `共${total_box_count}件`,
                    sku_en_title
                });
                const output = doc.getZip().generate({
                    type: "blob",
                    mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                    compression: "DEFLATE",
                });
                await zip.file(`${sku}_${total_box_count}PCS_${index+1}.doc`, output)
            }))
        }
    },
    {
        folderName: '外箱单',
        generateFile: async (zip, data) => {
            try {
                const {carton_label, order_no, package_label} = data
                if (carton_label) {
                    const res = await fetch(carton_label)
                    const blob = await res.blob()
                    if (package_label) {
                        const res2 = await fetch(carton_label)
                        const blob2 = await res2.blob()
                        zip.file(`箱单.pdf`, blob2)
                    }
                    zip.file(`箱唛_${order_no}.pdf`, blob)
                }
            } catch (error) {
                console.error('箱唛 Error:', error)
            }
        }
    },
    {
        folderName: '装箱资料',
        generateFile: async (zip, data) => {
            const { packing_data } = data
            if (!packing_data  || !Array.isArray(packing_data)) return
            const file = dataToXlsxBlob({
                data: packing_data,
                returnFileType: 'binary',
                headers: column_inspection_plan
            })
            await zip.file(`验货计划.xlsx`, binaryToBlob(file))
        }
    },
];

/**
 * 下载标签信息
 * @param orderNo 备库单号
 * @param orderType fba备货单：1 海外仓备库单：2 海外仓调拨单
 */
export default async (orderNo, data, orderType) => {
    const zip = new JSZip();
    await Promise.all(folderConfig.map(async (item, index) => {
        const currentFolder = zip.folder(item.folderName)
        if (item.generateFile) {
            await item.generateFile(currentFolder, data, orderType)
        }
    })).then(async () => {
        const content = await zip.generateAsync({ type: 'blob' })
        saveAs(content, `${orderNo}备库单号`)
    }).catch(e => {
        ElMessage.error(e)
    })
};